/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.liu.modules.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.JSONScanner;
import com.alipay.api.domain.SiteResult;
import com.liu.config.FileProperties;
import com.liu.domain.LocalStorage;
import com.liu.exception.BadRequestException;
import com.liu.modules.business.domain.NovelDetailInfo;
import com.liu.modules.business.domain.NovelInfo;
import com.liu.modules.business.repository.NovelInfoRepository;
import com.liu.modules.business.service.NovelInfoService;
import com.liu.modules.business.service.dto.NovelInfoDto;
import com.liu.utils.*;
import lombok.RequiredArgsConstructor;
import com.liu.modules.business.repository.NovelDetailInfoRepository;
import com.liu.modules.business.service.NovelDetailInfoService;
import com.liu.modules.business.service.dto.NovelDetailInfoDto;
import com.liu.modules.business.service.dto.NovelDetailInfoQueryCriteria;
import com.liu.modules.business.service.mapstruct.NovelDetailInfoMapper;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.util.*;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Liu
* @date 2022-07-04
**/
@Service
@RequiredArgsConstructor
public class NovelDetailInfoServiceImpl implements NovelDetailInfoService {

    private final NovelDetailInfoRepository novelDetailInfoRepository;
    private final NovelDetailInfoMapper novelDetailInfoMapper;
    private final FileProperties properties;
    private final NovelInfoService novelInfoService;
    private static Logger logger = Logger.getLogger("NovelDetailInfoServiceImpl");

    @Override
    public Map<String,Object> queryAll(NovelDetailInfoQueryCriteria criteria, Pageable pageable){
        Page<NovelDetailInfo> page = novelDetailInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Map<String, Object> novelInfoMap = PageUtil.toPage(page.map(novelDetailInfoMapper::toDto));
        List<NovelDetailInfoDto> NovelDetailInfoDtoList = (List<NovelDetailInfoDto>)novelInfoMap.get("content");
        for (NovelDetailInfoDto novelDetailInfoDto : NovelDetailInfoDtoList) {
            NovelInfoDto novelInfoDto = null;
            try{
                 novelInfoDto = novelInfoService.findById(novelDetailInfoDto.getNovelId());
                if(novelInfoDto != null){
                    novelDetailInfoDto.setNovelName(novelInfoDto.getNovelName());
                }
            }catch(Exception e){
                logger.warning(novelDetailInfoDto.getNovelId()+"is not exists");
            }

        }
        return novelInfoMap;
    }

    @Override
    public List<NovelDetailInfoDto> queryAll(NovelDetailInfoQueryCriteria criteria){
        List<NovelDetailInfoDto> novelDetailInfoDtos = novelDetailInfoMapper.toDto(novelDetailInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        for (NovelDetailInfoDto novelDetailInfoDto : novelDetailInfoDtos) {
            NovelInfoDto novelInfoDto = novelInfoService.findById(novelDetailInfoDto.getNovelId());
            if(novelInfoDto != null){
                novelDetailInfoDto.setNovelName(novelInfoDto.getNovelName());
            }
        }
        return novelDetailInfoDtos;
    }

    @Override
    @Transactional
    public NovelDetailInfoDto findById(String id) {
        NovelDetailInfo novelDetailInfo = novelDetailInfoRepository.findById(id).orElseGet(NovelDetailInfo::new);
        ValidationUtil.isNull(novelDetailInfo.getId(),"NovelDetailInfo","id",id);
        NovelDetailInfoDto novelDetailInfoDto = novelDetailInfoMapper.toDto(novelDetailInfo);
        NovelInfoDto novelInfoDto = novelInfoService.findById(novelDetailInfoDto.getNovelId());
        if(novelInfoDto != null){
            novelDetailInfoDto.setNovelName(novelInfoDto.getNovelName());
        }
        return novelDetailInfoMapper.toDto(novelDetailInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public NovelDetailInfoDto create(NovelDetailInfo resources) {
        resources.setId(IdUtil.simpleUUID()); 
        return novelDetailInfoMapper.toDto(novelDetailInfoRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(NovelDetailInfo resources) {
        NovelDetailInfo novelDetailInfo = novelDetailInfoRepository.findById(resources.getId()).orElseGet(NovelDetailInfo::new);
        ValidationUtil.isNull( novelDetailInfo.getId(),"NovelDetailInfo","id",resources.getId());
        novelDetailInfo.copy(resources);
        novelDetailInfoRepository.save(novelDetailInfo);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            novelDetailInfoRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<NovelDetailInfoDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (NovelDetailInfoDto novelDetailInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("novel_info表的主键", novelDetailInfo.getNovelId());
            map.put("章节名称", novelDetailInfo.getChapterTitle());
            map.put("章节内容", novelDetailInfo.getChapterText());
            map.put("创建时间", novelDetailInfo.getCreateTime());
            map.put("更新时间", novelDetailInfo.getUpdateTime());
            map.put("章节内容url", novelDetailInfo.getChapterUrl());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public NovelDetailInfoDto getNextNovelDetailInfo(NovelDetailInfoQueryCriteria criteria){
      return  novelDetailInfoMapper.toDto(novelDetailInfoRepository.getNextChapter(criteria.getChapterIndex(),criteria.getNovelId()));
    }

    public NovelDetailInfoDto getPrevNovelDetailInfo(NovelDetailInfoQueryCriteria criteria){
        return  novelDetailInfoMapper.toDto(novelDetailInfoRepository.getPrevChapter(criteria.getChapterIndex(),criteria.getNovelId()));
    }

    @Override
    public NovelDetailInfoDto upload(String novelId, String chapterTitle, MultipartFile multipartFile) {
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new BadRequestException("上传失败");
        }
        int maxChapterIndex = novelDetailInfoRepository.getMaxChapterIndex(novelId);
        maxChapterIndex++;
        String chapterText = "";
        if(suffix.equals("docx")||suffix.equals("doc")){
            XWPFDocument document = null;
            try{
                 document = new XWPFDocument(new FileInputStream(file));
            }catch (IOException exception){
                logger.info(exception.getMessage());
                throw new BadRequestException("word读取失败");
            }
            List<XWPFParagraph> paragraphList = document.getParagraphs();
            StringBuilder  builder = new StringBuilder();
            paragraphList.forEach(paragraph -> {
                String paragraphText = paragraph.getParagraphText();
                builder.append(paragraphText);
            });
            chapterText = builder.toString();
        }else{
            chapterText = FileUtil.readString(file, Charset.defaultCharset());
        }
        String s = FileUtil.readString(file, Charset.defaultCharset());
        try {
            NovelDetailInfo resources = new NovelDetailInfo();
            resources.setId(IdUtil.simpleUUID());
            resources.setChapterIndex( maxChapterIndex+"");
            resources.setChapterTitle(chapterTitle);
            resources.setNovelId(novelId);
            resources.setChapterText(chapterText);
            return novelDetailInfoMapper.toDto(novelDetailInfoRepository.save(resources));
        }catch (Exception e){
            FileUtil.del(file);
            throw e;
        }

    }
}